#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 15:38:02 2022

@author: mac1444
"""
import pulp as pl
import numpy as np
from pprint import pprint        #导入库函数
 
def transportation_problem(costs, x_max, y_max):
 
    row = len(costs)    #规定行数
    col = len(costs[0])   #规定列数
 
    prob = pl.LpProblem(sense=pl.LpMaximize)  #确定为线性规划的求最大值问题
 
    var = [[pl.LpVariable(f'x{i}{j}', lowBound=0, cat='Integer') for j in range(col)] for i in range(row)]  #规定变量，此处的f''是为了将x,y传给i,j
 
    flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]   #匿名函数，总而言之是为了变成一维数组
 
    prob += pl.lpDot(flatten(var), costs.flatten())      #做点积
 
    for i in range(row):        
        prob += (pl.lpSum(var[i]) <= x_max[i])           #lp计算序列的和，用lpsum比普通的sum快很多；此处属于添加条件使各作物小于计划播种面积
 
    for j in range(col):
        prob += (pl.lpSum([var[i][j] for i in range(row)]) <= y_max[j])
 
    prob.solve()
 
    return {'objective':pl.value(prob.objective), 'var': [[pl.value(var[i][j]) for j in range(col)] for i in range(row)]}
if __name__ == '__main__':
    costs = np.array([[500, 550, 630, 1000, 800, 700],
                       [800, 700, 600, 950, 900, 930],
                       [1000, 960, 840, 650, 600, 700],
                       [1200, 1040, 980, 860, 880, 780]])
 
    max_plant = [76, 88, 96, 40]
    max_cultivation = [42, 56, 44, 39, 60, 59]
    res = transportation_problem(costs, max_plant, max_cultivation)        #调用函数
 
    print(f'最大值为{res["objective"]}')
    print('各变量的取值为：')
    pprint(res['var'])